//
//  RCConectionHandler.m
//  CoreLocationTest
//
//  Created by Miles on 10-05-11.
//  Copyright 2010 Miles Thorogood
//  greenmeat.net. All rights reserved.
//  based off code from Rachel Simpson 

#import "RCConectionHandler.h"
#import "RCCommunicationController.h"

@implementation RCConectionHandler

@synthesize dataReceived;

- (id)initWithDelegate:(id)del {
    if (self = [super init]) {
        // Custom initialization
		conDelegate = del;
		self.dataReceived = [[[NSMutableData alloc] init] autorelease];
    }
	printf("ConnectionHandler: initWithDataReceiver\n");
    return self;
}

//The method is to deal with the connection
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	//The connection could be redirected multiple times
	//So we reset the data each time so we don't get a garbled response
	[dataReceived setLength:0];
	printf("ConnectionHandler: connection didReceiveResponse\n");
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	
	[dataReceived appendData:data];
	//	printf("ConnectionHandler: didReceiveData\n");
	//	printf("ConnectionHandler: received: %@\n", data);
	//	printf("ConnectionHandler: didReceiveData as a string:");
	//	NSString *aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];  
	//	NSLog(aStr);  
	//	printf("end NSLog\n");
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	//	[dataReceived release];
	[connection release];
	
	printf("ConnectionHandler: Connection didFailWithError\n");
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
	//Use dataReceived
	// do something with the data  
	// receivedData is declared as a method instance elsewhere  
	
	//NSLog(@"ConnectionHandler: connectionDidFinishLoading\nReceived %d bytes of data\n",[dataReceived length]);
	//NSLog(@"ConnectionHandler: dataReceived as a string:");
	//NSString *aStr = [[[NSString alloc] initWithData:dataReceived encoding:NSASCIIStringEncoding] autorelease];  
	//NSLog(@"%@",aStr);
	//NSLog(@"end NSLog\n");
	//[dataReceived release];
	
	[(RCCommunicationController *)conDelegate dataReceivedNotification:self];
	
	[connection release];
}


-(void)dealloc {
	[super dealloc];
	[dataReceived release];
}

@end
